import * as request from '../constant/fetchRequest'
import * as types from '../constant/action-types'
import HTTP_CODE from '../constant/httpCode'
import {message} from 'antd'
import {convertContent} from '../constant/lang-util'

export const getNotifications = (userId, status, page) => {
  return (dispatch) => {
    (async () => {
      const res = await request.get(`./api/notifications/users/${userId}?status=${status}&page=${--page}`)
      if (res.status === HTTP_CODE.OK) {
        dispatch({
          type: types.REFRESH_NOTIFICATIONS,
          status,
          notifications: res.body
        })
      }
    })()
  }
}

export const changeStatus = (notificationId, userId, status, callback) => {
  return (dispatch) => {
    (async () => {
      const res = await request.update(`./api/notifications/${notificationId}?status=${status}`)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        if (callback) {
          callback()
        } else {
          message.success(convertContent('标记成功'))
          dispatch(getNotifications(userId, 'read'))
          dispatch(getNotifications(userId, 'unRead'))
        }
      }
    })()
  }
}

export const markAllAsRead = (userId) => {
  return (dispatch) => {
    (async () => {
      const res = await request.update(`./api/notifications?status=read`)
      if (res.status === HTTP_CODE.NO_CONTENT) {
        message.success(convertContent('标记成功'))
        dispatch(getNotifications(userId, 'read'))
        dispatch(getNotifications(userId, 'unRead'))
      }
    })()
  }
}
